package com.doge.walknovel.api.model

import android.content.Context
import com.doge.walknovel.business.novel.NovelDetailActivity
import com.doge.walknovel.business.novel.NovelChapterPosHelper
import com.doge.walknovel.business.reader.ReaderActivity
import com.doge.walknovel.utils.isNullOrZero

data class NovelInfo(
    val novelId: Int,
    val coverUrl: String?,
    val title: String?,
    val description: String?,
    val author: String?,
    val firstChapterId: Int?,
    val recentChapterId: Int?,
    val chapterCount: Int?,
    val progress: Float?,
    var appReferId: Int? = null,
) {
    val readerChapterId: Int? get() {
        val cacheChapterId = NovelChapterPosHelper.loadCache(novelId)
        if (!cacheChapterId.isNullOrZero()) return cacheChapterId
        if (!recentChapterId.isNullOrZero()) return recentChapterId
        return firstChapterId
    }
    val percent get() = ((progress ?: 0f) / 100f) // 0-100

    companion object {
        fun form(data: NovelDetailInfo?): NovelInfo? {
            if (data == null) return null
            return NovelInfo(
                novelId = data.novelId,
                coverUrl = data.coverUrl,
                title = data.title,
                description = data.description,
                author = data.author,
                chapterCount = data.chapterCount,
                firstChapterId = data.firstChapterId,
                recentChapterId = data.recentChapterId,
                progress = data.progress,
            )
        }
    }
}

fun NovelInfo?.process(context: Context?, refer: String, referId: Int? = null) {
    if (this?.percent.isNullOrZero()) {
        NovelDetailActivity.start(context, this?.novelId, refer, referId)
    } else {
        ReaderActivity.start(context, this?.novelId, this?.readerChapterId, refer, referId)
    }
}

